var common = require("../../common/common.js");
var server = require("../../common/server.js");

var app = getApp();
Page({
  data: {
    goodsList: {
      saveHidden: true,
      totalPrice: 0,
      allSelect: true,
      noSelect: false,
      list: [],
    },
    delBtnWidth: 120,    //删除按钮宽度单位（rpx）,  
    nogoods: 'false'
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);  //以宽度750px设计稿做宽度的自适应
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  onLoad: function () {
    var that = this;
    that.setData({
      imgdir: app.globalData.imgdir
    })
  },
  /**
* 生命周期函数--监听页面初次渲染完成
*/
  onReady: function () {
  },
  onShow: function () {
    var that = this;
    that.initEleWidth();
    var shopList = [];
    // var goodsstr = '[{id:"10001",sysdate:"",pd_code:"1004",pd_name:"测试商品",pd_pic:"测试图片",sub_code:"10040070504",cr_code:"007",cr_name:"蓝色",sz_code:"05",sz_name:"xl",br_code:"04",br_name:"D",amount:"1",price:"99.0",companyid:"101",wu_code:"13654"}]';
    // var cartgoods = JSON.parse(goodsstr);
    

    

    // if (cartgoods) {
    //   that.data.goodsList.list = cartgoods;
    //   that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), cartgoods);
    //   that.setData({
    //     nogoods: 'false',
    //     cartgoods: cartgoods
    //   });

    // } else {

    //   that.setData({
    //     goodsList: {
    //       saveHidden: true,
    //       totalPrice: 0,
    //       allSelect: true,
    //       noSelect: false,
    //       list: [],
    //     },
    //     nogoods: 'true'
    //   });
    // }


    var company = app.globalData.currentCompany;
    if (!company) {
      wx.showToast({
        title: '商家信息不存在',
      })

      return false;
    }
    var user = app.globalData.user;
    if (!user) {
      wx.showToast({
        title: '登录用户不存在',
      })
      return false;
    }


    that.setData({
      controller: '/api/wx/cart/getCartInfo',
      params: {
        wu_code: user.wu_code,
        companyid: company.companyid
      }
    })

    common.doMethod({
      that: that,
      succFun: function (data) {
        if (data) {
          var cartgoods = data.data;
          if (cartgoods) {
            that.data.goodsList.list = cartgoods;
            that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), cartgoods);
            that.setData({
              nogoods: 'false',
              cartgoods: cartgoods
            });

          } else {

            that.setData({
              goodsList: {
                saveHidden: true,
                totalPrice: 0,
                allSelect: true,
                noSelect: false,
                list: [],
              },
              nogoods: 'true'
            });
          }
        }
      }
    })
  },
  toIndexPage: function () {
    wx.switchTab({
      url: "/pages/shop/shop"
    });
  },

  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    var index = e.currentTarget.dataset.index;

    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      } else if (disX > 0) {//移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          left = "left:-" + delBtnWidth + "px";
        }
      }
      var list = this.data.goodsList.list;
      if (index != "" && index != null) {
        list[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
      }
    }
  },

  touchE: function (e) {
    var index = e.currentTarget.dataset.index;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      var list = this.data.goodsList.list;
      if (index !== "" && index != null) {
        list[parseInt(index)].left = left;
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

      }
    }
  },
  selectTap: function (e) {

    var that = this;
    const index = e.currentTarget.dataset.index;        // 获取data- 传进来的index
    var list = that.data.goodsList.list;             // 获取购物车列表
    const active = list[index].active;         // 获取当前商品的选中状态
    list[index].active = !active;              // 改变状态

    that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);

  },
  totalPrice: function () {

    var that = this;


    var list = this.data.goodsList.list;
    var amount = 0;
    var total = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        // if (that.data.member.is_member == 1) {
        //   total += parseFloat(curItem.memberprice) * curItem.amount;;

        // } else {
        total += parseFloat(curItem.price) * curItem.amount;
        }
        //total += parseFloat(curItem.price) * curItem.amount;
      // }
    }

    var preid = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (preid == 0 || preid != curItem.id) {
        if (curItem.active) {
          amount++;
          preid = curItem.id;
        }
      }
    }

    return total;
  },
  allSelect: function () {
    var list = this.data.goodsList.list;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },
  noSelect: function () {
    var list = this.data.goodsList.list;
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == list.length) {
      return true;
    } else {
      return false;
    }
  },
  setGoodsList: function (saveHidden, total, allSelect, noSelect, list) {
    var that = this;

    //重新获取member数据，赋值全局
    //app.getUserInfo({
      //success: function () {
        // var member = app.globalData.member;
        // that.setData({
        //   member: member
        // })
        // for (var m = 0; m < list.length; m++) {
        //   var cartgood = list[m];
        //   //if (cartgood.id == that.data.id) {
        //   // if (that.data.member.is_member == 1) {
        //   //   cartgood.price = cartgood.memberprice;

        //   // } else {
        //     cartgood.price = cartgood.saleprice;
        //   // }
        // }

        
        var shopCarInfo = [];
        for (var i = 0; i < list.length; i++) {
          if (list[i].pd_pic.indexOf('http:')<0){
            list[i].pd_pic = that.data.imgdir + list[i].pd_pic;
          }          
          if (list[i].active) {
            shopCarInfo.push(list[i]);
          }
        }

        that.setData({
          shopCarInfo: shopCarInfo
        })

        that.setData({
          goodsList: {
            saveHidden: saveHidden,
            totalPrice: total.toFixed(2),
            allSelect: allSelect,
            noSelect: noSelect,
            list: list
          }
        });

      //}
    //})
  },
  bindAllSelect: function () {
    var that = this;
    var currentAllSelect = this.data.goodsList.allSelect;
    var list = this.data.goodsList.list;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = false;

        that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);
      }
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = true;

        that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);
      }
    }

    this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), list);
  },
  jiaBtnTap: function (e) {
    var that = this;
   

    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      var modifycartgoods=list[parseInt(index)];
      var amount = modifycartgoods.amount + 1;
      that.setData({
        action: 'modifyCartNum',
        id: modifycartgoods.id,
        amount: amount
      })
      
      that.modify();      
    }

    // var index = e.currentTarget.dataset.index;
    // var list = this.data.goodsList.list;
    // if (index !== "" && index != null) {
    //   list[parseInt(index)].num++;
    //   wx.showToast({
    //     title: '数量更新成功',
    //     icon: 'none'
    //   });
    //   that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);

    //   that.data.cartgoods[parseInt(index)].num++;

    //   //wx.setStorageSync("cartgoods", that.data.cartgoods);
    // }
  },
  jianBtnTap: function (e) {
    var that = this;
  
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      var modifycartgoods = list[parseInt(index)];
      var amount = modifycartgoods.amount - 1;
      if (amount == 0) {
        var ids=[];
        ids.push(modifycartgoods.id)
        that.setData({
          ids: ids,
          amount: amount
        })
        that.delete();
      } else {
        that.setData({
          action: 'modifyCartNum',
          id: modifycartgoods.id,
          amount: amount
        })
        that.modify();
      }
    }
    // var index = e.currentTarget.dataset.index;
    // var list = this.data.goodsList.list;
    // if (index !== "" && index != null) {
    //   if (list[parseInt(index)].num > 1) {
    //     list[parseInt(index)].num--;
    //     wx.showToast({
    //       title: '数量更新成功',
    //       icon: 'none'
    //     });
    //     that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);

    //     that.data.cartgoods[parseInt(index)].num--;

    //     //wx.setStorageSync("cartgoods", that.data.cartgoods);
    //   }
    // }
  },
  editTap: function () {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  saveTap: function () {
    var list = this.data.goodsList.list;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      curItem.active = false;
    }
    this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
  },
  getSaveHide: function () {
    var saveHidden = this.data.goodsList.saveHidden;
    return saveHidden;
  },
  deleteSelected: function () {
    var that = this;

    var ids = [];
    
    var list = this.data.goodsList.list;
    //var cartids = "";
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        //cartids += curItem.id + ",";
        ids.push(curItem.id)
      }
    }
    // if (cartids == "") {
    if (ids.length == 0){
      wx.showToast({
        title: '没有要删除的数据',
      });
      return;
    } else {

      // var deletecartgoods=[];
      // for (var i = 0; i < list.length; i++) {
      //   var curItem = list[i];

      //   if (curItem.active) {
      //     deletecartgoods.push(curItem);
      //   }
      // }
      // that.setData({
      //   deletecartgoods: deletecartgoods
      // });

      that.setData({
        ids: ids
      })
      that.delete();

      // for (var i = 0; i < list.length; i++) {
      //   var curItem = list[i];

      //   if (curItem.active) {
      //     that.data.cartgoods.splice(i, 1);
      //     list.splice(i, 1);
      //     i = -1;
      //   }
      // }

      // //wx.setStorageSync("cartgoods", that.data.cartgoods);
      // that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);

      //删除后自动恢复去结算状态
      that.saveTap();
    }

  },
  toPayOrder: function () {
    var that = this;
    //var list = this.data.goodsList.list;
    // this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);

    if (that.data.shopCarInfo.length == 0) {
      wx.showToast({
        title: '还没有选择商品哦',
        icon: 'none'
      })
      return false;
    }
    wx.showToast({
      title: "订单中心",//data.data"",
      icon: 'loading',
      duration: 3000,
      success: function (res) {
        wx.setStorage({
          key: 'shopCarInfo',
          data: that.data.shopCarInfo,
          success: function (res) {
            wx.navigateTo({
              url: '/pages/paycenter/order'
            })
          }
        })
      }
    })

  },
  navigateToPayOrder: function () {
    wx.hideLoading();
    wx.navigateTo({
      url: "/pages/to-pay-order/index"
    })
  },
  //购物车商品数量加减处理
  modify: function (e) {
    var that = this;

    that.setData({
      controller: '/api/wx/cart/' + that.data.action,
      params: {
        id: that.data.id,
        amount:that.data.amount
      }
    })

    common.doMethod({
      that: that,
      succFun: function (data) {
        wx.showToast({
          title: '数量更新成功',
          icon: 'none',
          success: function () {
            if (data){
              var list = that.data.goodsList.list;
              for (var i = 0; i < list.length; i++) {
                var curItem = list[i];
                if (that.data.id == curItem.id) {
                  curItem.amount = that.data.amount;
                }
              }
              //that.data.goodsList.list = data.data;
              that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);
              that.setData({
                nogoods: 'false',
                // cartgoods: cartgoods
              });
            }
            
          }
        }); 
      }
    })
    
  },
  //购物车删除
  delete: function (e) {
    var that = this;

    wx.showModal({
      title: '提示',
      content: '确定删除吗！',
      success:function(e){
        if (e.confirm){
          that.setData({
            controller: '/api/wx/cart/deleteCart',
            params: {
              ids: that.data.ids
            }
          })

          common.doMethod({
            that: that,
            succFun: function (data) {
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                success: function () {
                  if (data) {

                    var list = that.data.goodsList.list;
                    for (var i = 0; i < list.length; i++) {
                      var curItem = list[i];
                      for (var k = 0; k < that.data.ids.length; k++) {
                        var cartid = that.data.ids[k];
                        if (cartid == curItem.id) {
                          list.splice(i, 1);
                          i = -1;
                        }
                      }
                    }

                    that.data.goodsList.list = list;
                    that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list);
                  }
                }
              });
            }
          })
        }
      }
    })
  }
})
